var ServiceUrl = 'http://localhost:54502/API/';
var homeLoaded = 0;
var user, currentItem, profileEmail, currentOrder;

$(document).on("mobileinit", function(){
               $.mobile.defaultPageTransition = "none";
               $.defaultDialogTransition = "none";
               $.mobile.transitionFallbacks.slideout = "none";
               $.mobile.ajaxEnabled="true";
               $.mobile.orientationChangeEnabled = "false";
               $.mobile.zoom.enable(false);
               
});

function InitialStorage() {
    localStorage.isLogin = 0;           
               
    localStorage.logInURL = ServiceUrl + 'UserAccount/LogIn?';
    localStorage.registerURL = ServiceUrl + 'UserAccount/Register?';
    localStorage.editInfoURL = ServiceUrl + 'UserAccount/Edit?';
    
    localStorage.addNewPropertyURL = ServiceUrl + 'UserStuff/Insert?';
    localStorage.editPropertyURL = ServiceUrl + 'UserStuff/Update?';
    localStorage.getUserPropertiesURL = ServiceUrl + 'UserStuff/Get?';
    localStorage.removePropertyURL = ServiceUrl + 'UserStuff/Delete?';
    localStorage.setItemPriceURL = ServiceUrl + 'UserStuff/SetPrice?';
    
    localStorage.getAllPropertiesURL = ServiceUrl + 'Shopping/GetStuffs?';
    localStorage.orderStuffURL = ServiceUrl + 'Shopping/OrderStuff?';
    
    localStorage.getOwnerProfileURL = ServiceUrl + 'Profile/GetProfile?';
    localStorage.rateUserURL = ServiceUrl + 'Profile/Vote?';

	localStorage.shopPageLoaded = 0;
	
	localStorage.getReceivedOrderURL = ServiceUrl + 'UserOrder/GetOrders?';
	localStorage.getSentOrderURL = ServiceUrl + 'UserOrder/GetSentOrders?';

}

function CheckLogin(){
	if (localStorage.isLogin == 0)
		$.mobile.changePage("#signIn", { transition: "none" });
}

function LogOut(){
	localStorage.keepLogin = 0;
				
	localStorage.email = '';
	localStorage.password = '';
	localStorage.userId = 0;
	
	localStorage.isLogin = 0;
	
        $('#login-email').val('');
        $('#login-password').val('');
        
        $.mobile.changePage("#signIn", { transition: "slide", reverse: "true" });
        localStorage.shopPageLoaded = 0;
        $('#shopListView').html('');
}

function validateEmail(email) 
{
    var re = /\S+@\S+\.\S+/;
    return re.test(email);
}

function SignIn(){
	var email = $('#login-email').val();
	var password = $('#login-password').val();
	if (!validateEmail(email) || password == '')  {
		alert('Invalid email or password');
		return;
	}
	$.mobile.loading("show");
	{
		localStorage.isLogin = 0;
		var jqxhr = $.ajax({
			type: "GET",
			url: localStorage.logInURL + 'email=' + email + '&password=' + password,
			dataType: "json",
			success: function(data)	{
				if (data[0] == 'success')
				{
							if ($('#keep-login').is(':checked'))
								localStorage.keepLogin = 1;								
							else 
								localStorage.keepLogin = 0;
								
							localStorage.email = email;
							localStorage.password = password;
							localStorage.isLogin = 1;
							user = data[1];
							homeLoaded = 0;

							$.mobile.changePage( "#home", {
								transition: "slide",
							});
				} else {
					alert('Incorrect password or email!');
				}
			},
			error: function(data) {
				alert('Service Error');
			},
			complete: function(jqXHR,status) {
			    $.mobile.loading("hide");
                            $('#login-password').val('');
			}
		});
	}
}

function SignUp() {
    var email = $('#signup-email').val();
	var password = $('#signup-password').val();
    var firstName = $('#signup-firstname').val();
    var lastName = $('#signup-lastname').val();
	
	if (!validateEmail(email)) {
		alert('Invalid email form');
		return;
	}
	
    if (password.length < 6) {
        alert('Password must be longer than 6 characters');
        return;
    }
    
	if (password == '' || firstName == '' || lastName == '') {
		alert('All field can not be left empty');
		return;
	}
	
    if ($('#signup-password').val() != $('#signup-confirm-password').val()) {
        alert('Please Confirm Password!');
        return;
    } 
	else {
		$.mobile.loading("show");
		localStorage.isLogin = 0;
		var jqxhr = $.ajax({
			type: "GET",
			url: localStorage.registerURL + 'email=' + email + '&password=' + password + '&firstname=' + firstName + '&lastname=' + lastName,
			dataType: "json",
			success: function(data)	{
				if (data[0] == 'success')
				{
							localStorage.isLogin = 1;
                            homeLoaded = 0;                          
                            user = data[1];

							$.mobile.changePage( "#home", {
								transition: "slide",
							});
							alert('Registered successfully!');
				} else {
					alert(data[1]);
				}
			},
			error: function(data) {
				alert('Service Error');
			},
			complete: function(jqXHR,status) {
                              $.mobile.loading("hide");
                              $('#signup-email').val('');
                              $('#signup-password').val('');
                              $('#signup-confirm-password').val('');
                              $('#signup-firstname').val('');
                              $('#signup-lastname').val('');
			}
		});
	}
}

$(document).on("pageinit", "#edit-page", function(event) {
	$('#edit-firstname').val(user.FirstName);
	$('#edit-lastname').val(user.LastName);
});

function EditInfo() {
    if ($('#edit-password').val() != $('#edit-confirm-password').val()) {
        alert('Please Confirm Password!');
        return;
    } else
        {
		var password = $('#edit-password').val();
                var firstName = $('#edit-firstname').val();
                var lastName = $('#edit-lastname').val();
				var oldPassword = $('#edit-old-password').val();
            if (password.length < 6 && password.length > 0) {
                alert('Password must be longer than 6 characters');
                return;
            }
        $.mobile.loading("show");
		var jqxhr = $.ajax({
			type: "GET",
			url: localStorage.editInfoURL + 'Id=' + user.Id + '&password=' + password + '&firstname=' + firstName + '&lastname=' + lastName + '&confirmPassword=' + oldPassword,
			dataType: "json",
			success: function(data)	{
				if (data[0] == 'success')
				{
							localStorage.isLogin = 1;
                            homeLoaded = 0;                            
                            user = data[1];

							$.mobile.changePage( "#home", {
								transition: "slide",
							});
				} else {
					alert(data[1]);
				}
			},
			error: function(data) {
				alert('Service Error');
			},
			complete: function(jqXHR,status) {
			    $.mobile.loading("hide");
                            $('edit-password').val('');
                            $('edit-confirm-password').val('');
                            $('edit-firstname').val('');
                            $('edit-lastname').val('');
			}
		});
	}
}
/*** ====== Basic Pages ====== ***/
$(document).on("pageinit", "#signIn", function(event) {
	$('#login-email').val('');
	$('#login-password').val('');
	
	homeLoaded = 0;	
	
	if (localStorage.keepLogin == 1 && localStorage.email != '' && localStorage.password != '')
	{
		var jqxhr = $.ajax({			
			url: localStorage.logInURL + 'email=' + localStorage.email + '&password=' + localStorage.password,
			dataType: "json",
			success: function(data)	{
				localStorage.isLogin = 1;
                              user = data[1];

				$.mobile.changePage( "#home", {
					transition: "none",
				});
			},
                        error: function(data) {
				alert('Service Error');
			},
			complete: function(jqXHR,status) {
			}
		});
	}
});

$(document).on('pagebeforeshow', '#home', function(event) {
	CheckLogin();
  if (homeLoaded == 0) {
	$.mobile.loading("show");
	$('#userInfo').html('');
	var htmlString = '<h2 align="center">User Info</h2><div class="clearer">&nbsp;</div>'; 
	htmlString = htmlString + '<b><img style="height:1.25em; width:1.25em;" src="./img/i-user.png"> Username:</b> ' + user.FirstName + ' ' + user.LastName + '<div class="clearer">&nbsp;</div>'
                        + '<b><img style="height:1.25em; width:1.25em;padding-top:1px;" src="./img/i-email.png"> Email:</b> '
			+ user.Email + '<div class="clearer">&nbsp;</div><b>Trust Rank: </b>';
    for (var i = 0; i < user.TrustRank; i++)
               htmlString = htmlString + '<img src="./img/star.png" style="width:1.5em;height:1.5em;">';

	$('#userInfo').html(htmlString);
	
	homeLoaded = 1;
  }
});

$(document).on('pageshow', '#received-order-page', function (event) {
				$('#receivedOrderListView').html('');
               var jqxhr = $.ajax({
								  type: "GET",
                                  url: localStorage.getReceivedOrderURL + 'userId=' + user.Id,
                                  dataType: "json",
                                  success: function(data)	{
                                  if (data[0] == 'success') {
									  if (data[1] !== null) {
										  for (var i=0; i < data[1].length; i++) {
										  $('#receivedOrderListView').append('<li><a href="javascript:LoadReceivedOrderDetail(' + i + ');" data-transition="slide"><h2>' + data[1][i].UserStuff.Name + '</h2><p>' + data[1][i].ModifiedDateTime + '</p></a></li>');
										  $('#receivedOrderListView').listview('refresh');
										  }
										  
										  localStorage.receivedOrderData = JSON.stringify(data[1]);
										  }
                                  }
                                  else if (data[0] == 'failure') {
									alert(data[1]);
                                  }
                                  },
                                  error: function(data) {
                                  alert('Service Error');
                                  },
                                  complete: function(jqXHR,status) {
                                  $.mobile.loading("hide");
                                  }
                                  });

});

function LoadReceivedOrderDetail(i) {
	localStorage.propertyItemTapped = i;
	$.mobile.changePage("#received-order-detail-page", { transition: "slide", });
}

$(document).on('pagebeforeshow', '#received-order-detail-page', function(event) {
               try
               {
                       var data = JSON.parse(localStorage.receivedOrderData);
                       currentOrder = data[localStorage.propertyItemTapped];
					   profileEmail = currentOrder.OrderUserEmail;
               }
               catch (err) {}
               $('#receivedOrderDetail').html('');
               var htmlString = '<p><img style="height:1.5em; width:1.5em;" src="./img/i-user.png"><b> Sender: </b><a href="#profile-page" data-transition="slide">' + currentOrder.OrderUserEmail +
			   '</a></p><p><img style="height:1.5em; width:1.5em;" src="./img/i-money.png"><b> Offer Money: </b>$' + currentOrder.OfferMoney +
			   '</p><div class="clearer">&nbsp;</div><p><b>Item Name: </b>' + currentOrder.UserStuff.Name +
			   '</p><p><b>Price: </b>$' + currentOrder.UserStuff.UnitPrice +
			   '</p><p><b>Description: </b>' + currentOrder.UserStuff.Description +
			   '</p><p><b>Last updated: </b>' + currentOrder.ModifiedDateTime + '</p>';
               $('#receivedOrderDetail').html(htmlString);
});

$(document).on('pageshow', '#sent-order-page', function (event) {
				$('#sentOrderListView').html('');
               var jqxhr = $.ajax({
								  //type: "GET",
                                  url: localStorage.getSentOrderURL + 'userId=' + user.Id,
                                  dataType: "json",
                                  success: function(data)	{
                                  if (data[0] == 'success') {
									  if (data[1] !== null) {
										  for (var i=0; i < data[1].length; i++) {
										  $('#sentOrderListView').append('<li><a href="javascript:LoadSentOrderDetail(' + i + ');" data-transition="slide"><h2>' + data[1][i].UserStuff.Name + '</h2><p>Last update: ' + data[1][i].ModifiedDateTime + '</p></a></li>');
										  $('#sentOrderListView').listview('refresh');
										  }
										  
										  localStorage.sentOrderData = JSON.stringify(data[1]);
									  }
                                  }
                                  else if (data[0] == 'failure') {
									alert(data[1]);
                                  }
                                  },
                                  error: function(data) {
                                  alert('Service Error');
                                  },
                                  complete: function(jqXHR,status) {
                                  $.mobile.loading("hide");
                                  }
                                  });

});

function LoadSentOrderDetail(i) {
	localStorage.propertyItemTapped = i;
	$.mobile.changePage("#sent-order-detail-page", { transition: "slide", });
}

$(document).on('pagebeforeshow', '#sent-order-detail-page', function(event) {
               try
               {
                       var data = JSON.parse(localStorage.sentOrderData);
                       currentOrder = data[localStorage.propertyItemTapped];
					   profileEmail = currentOrder.OwnerUserEmail;
               }
               catch (err) {}
               $('#sentOrderDetail').html('');
               var htmlString = '<p><img style="height:1.5em; width:1.5em;" src="./img/i-user.png"><b> Receiver: </b><a href="#profile-page" data-transition="slide">' + currentOrder.OwnerUserEmail +
			   '</a></p><p><img style="height:1.5em; width:1.5em;" src="./img/i-money.png"><b> Offer Money: </b>$' + currentOrder.OfferMoney +
			   '</p><div class="clearer">&nbsp;</div><p><b>Item Name: </b>' + currentOrder.UserStuff.Name +
			   '</p><p><b>Price: </b>$' + currentOrder.UserStuff.UnitPrice +
			   '</p><p><b>Description: </b>' + currentOrder.UserStuff.Description +
			   '</p><p><b>Last updated: </b>' + currentOrder.ModifiedDateTime + '</p>';
               $('#sentOrderDetail').html(htmlString);
});

/*** ====== User Property Pages ====== ***/
$(document).on('pagebeforeshow', '#properties-page', function(event) {             
               $('#userPropertiesListView').html('');
			   $.mobile.loading('show');
               var jqxhr = $.ajax({
							  type: "GET",
                              url: localStorage.getUserPropertiesURL + 'userId=' + user.Id,
                              dataType: "json",
                              success: function(data)	{
                                        if (data[0] == 'success') {
											if (data[1] == null) {
												$('#userPropertiesListView').insertBefore('No data');
											} else {
										
                                             for (var i=0; i < data[1].length; i++) {
                                                            $('#userPropertiesListView').append('<li><a href="javascript:LoadPropertyDetail(' + i + ');" data-transition="slide">' + data[1][i].Name + '</a></li>');
                                                            $('#userPropertiesListView').listview('refresh');
                                             }
                                             
                                             localStorage.propertyData = JSON.stringify(data);
											 }
                                        }
                                        else if (data[0] == 'failure') {
                                             alert(data[1]);
                                        }
               		      },
                              error: function(data) {
				alert('Service Error');
                              },
                              complete: function(jqXHR,status) {
                                  $.mobile.loading("hide");
                              }
               });
});

$(document).on('pagebeforeshow', '#add-property-page', function(event) {
            $('#txtItemName').val('');
            $('#txtItemPrice').val('');
            $('#txtaItemDescription').val('');
});

function LoadPropertyDetail(i) {
	localStorage.propertyItemTapped = i;
	$.mobile.changePage("#property-detail-page", { transition: "slide", });
}

$(document).on('pagebeforeshow', '#property-detail-page', function(event) {
               try
               {
                       var data = JSON.parse(localStorage.propertyData);
                       currentItem = data[1][localStorage.propertyItemTapped];
               }
               catch (err) {}
               $('#propertyDetail').html('');
               var htmlString = '<p><b>Item Name: </b>' + currentItem.Name + '</p><p><b>Price: </b>$' + currentItem.UnitPrice + '</p><p><b>Description: </b>' + currentItem.Description + '</p><p><b>Last updated: </b>' + currentItem.ModifiedDateTime + '</p>';
               $('#propertyDetail').html(htmlString);
});

$(document).on('pagebeforeshow', '#add-property-page', function(event) {
            $('#txtItemName').val('');
            $('#txtItemPrice').val('');
            $('#txtaItemDescription').val('');
			
			var jqxhr = $.ajax({
				type: "GET",
				url: ServiceUrl + 'Shopping/GetCategories?userId=' + user.Id,
				dataType: "json",
				success: function (data) {
					var html = '';
					for (var i = 0; i < data[1].length; i++)
						html += '<option value="' + data[1][i].Id + '">' + data[1][i].Name + '</option>';
					$("#ddlCategories").html(html);
					$("#ddlCategories").selectmenu("refresh");;
				},
				error: function (data) {
					alert('Service Error');
				},
				complete: function(jqXHR,status) {
				
				}
			});
});

function AddNewProperty() {
               $.mobile.loading("show");
	       var itemName = $('#txtItemName').val();
	       var itemPrice = $('#txtItemPrice').val();
               var itemCategory = $('#scItemCategory').val();
               var itemDescription = $('#txtaItemDescription').val();
               var categoryId = $('#ddlCategories').val();
			if (!isNumber(itemPrice)) {
				alert('Price must be in number');
				return;
			}
	       var jqxhr = $.ajax({
			type: "POST",
			url: localStorage.addNewPropertyURL + 'userId=' + user.Id + '&name=' + itemName + '&categoryId=' + categoryId + '&price=' + itemPrice + '&description=' + itemDescription,
			dataType: "json",
			success: function(data)	{
				if (data[0] == 'success')
				{
							$.mobile.changePage( "#properties-page", {
								transition: "slide",
							});
				} else {
					alert(data[1]);
				}
			},
			error: function(data) {
				alert('Service Error');
			},
			complete: function(jqXHR,status) {
			    $.mobile.loading("hide");
			}
	       });
}

function isNumber (o) {
  return ! isNaN (o-0) && o !== null && o !== "" && o !== false;
}

$(document).on('pageshow', '#edit-property-page', function(event) {
	$('#txtEditItemName').val(currentItem.Name);
		$('#txtEditItemPrice').val(currentItem.UnitPrice);
		$('#txtaEditItemDescription').val(currentItem.Description);
		
		var jqxhr = $.ajax({
				type: "GET",
				url: ServiceUrl + 'Shopping/GetCategories?userId=' + user.Id,
				dataType: "json",
				success: function (data) {
					var html = '';
					for (var i = 0; i < data[1].length; i++)
						html += '<option value="' + data[1][i].Id + '">' + data[1][i].Name + '</option>';
					$("#ddlEditCategories").html(html);
					$("#ddlEditCategories").selectmenu("refresh");;
				},
				error: function (data) {
					alert('Service Error');
				},
				complete: function(jqXHR,status) {
				
				}
			});
});

function EditProperty() {       
		var itemName = $('#txtEditItemName').val();
		var itemPrice = $('#txtEditItemPrice').val();
                var itemCategory = $('#ddlEditItemCategory').val();
                var itemDescription = $('#txtaEditItemDescription').val();
                
                $.mobile.loading("show");
		var jqxhr = $.ajax({
			type: "POST",
			url: localStorage.editPropertyURL + 'userId=' + user.Id + '&stuffId=' + currentItem.Id + '&name=' + itemName + '&price=' + itemPrice + '&description=' + itemDescription + '&categoryId=' + itemCategory,
			dataType: "json",
			success: function(data)	{
				if (data[0] == 'success')
				{
					     $.mobile.changePage( "#properties-page", {
							    transition: "slide",
                                                            direction: "reverse",
					     });
				} else {
					alert(data[1]);
				}
			},
			error: function(data) {
				alert('Service Error');
			},
			complete: function(jqXHR,status) {
			    $.mobile.loading("hide");
			}
		});
}

function RemoveProperty() {
               var r=confirm("Are you sure you want to remove this item?");
               if (r == true) {
                              $.mobile.loading('show');
                              var jqxhr = $.ajax({
                                       type: "POST",
                                       url: localStorage.removePropertyURL + 'userId=' + user.Id + '&stuffId=' + currentItem.Id,
                                       dataType: "json",
                                       success: function(data)	{
                                               if (data[0] == 'success')
                                               {
                                                            $.mobile.changePage( "#properties-page", {
                                                                           transition: "slide",
                                                                           direction: "reverse",
                                                            });
                                                            alert('Item removed successfully!');
                                               }
                                               else {
                                                       alert(data[1]);
                                               }
                                       },
                                       error: function(data) {
                                               alert('Service Error');
                                       },
                                       complete: function(jqXHR,status) {
                                           $.mobile.loading("hide");
                                       }
                               });           
               }
}

/*** ====== Shopping Pages ====== ***/
function LoadShopPropertyDetail(i) {
	localStorage.shopPropertyItemTapped = i;
	$.mobile.changePage("#shop-property-detail-page", { transition: "slide", });
}

$(document).on('pagebeforeshow', '#shop-property-detail-page', function(event) {
               try
               {
                       var data = JSON.parse(localStorage.shopPropertyData);
                       currentItem = data[1][localStorage.shopPropertyItemTapped];
					   profileEmail = currentItem.UserEmail;
               }
               catch (err) {}
               $('#shopPropertyDetail').html('');
               var htmlString = '<p><b>Item Name: </b>' + currentItem.Name + '</p><p><b>Description: </b>' + currentItem.Description + '</p><p><b>Price: </b>$' + currentItem.UnitPrice + '</p><p><b>Last updated: </b>' + currentItem.ModifiedDateTime + '</p><p><b>Owner: </b><a href="#profile-page" data-transition="none">' + currentItem.UserEmail + '</a></p>';
               $('#shopPropertyDetail').html(htmlString);
});

$(document).on('change', '#shopCategoryList', function(event) {
				var urlString = localStorage.getAllPropertiesURL + 'userId=' + user.Id;
				if ($('#shopCategoryList').val() != 0)
					urlString = urlString + '&categoryId=' + $('#shopCategoryList').val();

               $.mobile.loading('show');
               var jqxhr = $.ajax({
                              type: "GET",
                              url: urlString,
                              dataType: "json",
                              success: function(data) {
                                             $('#userPropertiesListView').html('');
                                             $('#shopListView').html('');
                                             if (data[1] == null) {
									   $('#userPropertiesListView').insertBefore('No data');
							    }
                                                            else {			
                                                                           for (var i=0; i < data[1].length; i++) {
                                                                                          $('#shopListView').append('<li><a href="javascript:LoadShopPropertyDetail(' + i + ');" data-transition="slide">' + data[1][i].Name + '</a></li>');
                                                                           $('#shopListView').listview('refresh');
                                                            }
                                             
                                                                           localStorage.shopPropertyData = JSON.stringify(data);      
                                                            }
                              },
                              error: function(data) {
                                             $.mobile.loading('hide');  
                                             alert('Service Error');             
                              },
                              complete: function(data) {
                                           $.mobile.loading('hide');  
                              },
               });
});

$(document).on('pageshow', '#shop-page', function(event) {
	if (localStorage.shopPageLoaded == 0) {
               $.mobile.loading('show');
			   var jqxhr = $.ajax({
				type: "GET",
				url: ServiceUrl + 'Shopping/GetCategories?userId=' + user.Id,
				dataType: "json",
				success: function (data) {
					var html = '<option value="0" class="one"> All </option>';
					for (var i = 0; i < data[1].length; i++)
						html += '<option value="' + data[1][i].Id + '">' + data[1][i].Name + '</option>';
					$("#shopCategoryList").html(html);
					$("#shopCategoryList").selectmenu("refresh");;
				},
				error: function (data) {
					alert('Service Error');
				},
				complete: function(jqXHR,status) {
				
				}
			});
               var jqxhr = $.ajax({
                              type: "GET",
                              url: localStorage.getAllPropertiesURL + 'userId=' + user.Id,
                              success: function(data) {
                                             if (data[0] == 'success') {
                                                            if (data[1] == null) {
									   $('#shopListView').insertBefore('No data');
							    }
                                                            else {			
                                                                           for (var i=0; i < data[1].length; i++) {
                                                                                          $('#shopListView').append('<li><a href="javascript:LoadShopPropertyDetail(' + i + ');" data-transition="slide">' + data[1][i].Name + '</a></li>');
                                                                           $('#shopListView').listview('refresh');
                                                            }
                                             
                                                                           localStorage.shopPropertyData = JSON.stringify(data);
																			localStorage.shopPageLoaded = 1;
                                                            }
                                             }
                                             else {
                                                            alert(data[1]);
                                             }
                              },
                              error: function(data) {
                                             alert('Service Error');
                              },
                              complete: function(data) {
                                             $.mobile.loading('hide');
											 
                              }
               });
	}
});
function SendOrder() {
    if (!isNumber($('#transaction-money').val()) && $('#transaction-money').val().length > 0)
    {
        alert('Money must be in number!');
        return;
    }
    $.mobile.loading('show');
    var jqxhr = $.ajax({
                       type: "POST",
                       url: localStorage.orderStuffURL + 'userId=' + user.Id + '&stuffId=' + currentItem.Id + '&paymentType=' + $('#paymentType').val() + '&offerMoney=' + $('#transaction-money').val(),
                       success: function(data) {
							if (data[0] = 'success') {
								alert('Order has been sent!');
								$.mobile.changePage('#shop-page');
							}
							else
								alert(data[1]);
                       },
                       error: function (data) {
                       alert('Service Error');
                       },
                       complete: function(data) {
                       $.mobile.loading('hide');
                       }
    });
}
/*** ====== Profile Detail Pages ====== ***/
$(document).on('pageshow', '#profile-page', function(event) {
               $.mobile.loading('show');
               var jqxhr = $.ajax({
                                  type: "GET",
                                  url: localStorage.getOwnerProfileURL + 'userId=' + user.Id + '&profileEmail=' + profileEmail,
                                  success: function(data) {
                                            if (data[0] == 'success')
                                            {
                                                var htmlString = '';
                                                htmlString = htmlString + '<p><b><img style="height:1.25em; width:1.25em;" src="./img/i-email.png"> Email: </b>' + data[1].Email + '</p><p><b><img style="height:1.25em; width:1.25em;" src="./img/i-user.png"> Name: </b>' + data[1].FirstName + ' ' + data[1].LastName + '</p><p><b>Trust Rank: </b>';
                                                for (var i = 0; i < data[1].TrustRank; i++)
                                                    htmlString = htmlString + '<img src="./img/star.png" style="width:1.5em;height:1.5em;">';
                                                htmlString = htmlString + '</p>';
                                                $('#profileDetail').html(htmlString);
                                            }
											else
												alert(data[1]);
                                  },
                                  error: function(data) {
                                    alert('Service Error');
                                  },
                                  complete: function(data) {
                                    $.mobile.loading('hide');
                                  
                                  }
                });
});
function SubmitRating()
{
    var jqxhr = $.ajax({
                       type: "POST",
                       url: localStorage.rateUserURL + 'userId=' + user.Id + '&profileEmail=' + profileEmail + '&rank=' + $('#ddlRate').val(),
					   dataType: "json",
                       success: function(data) {
                        if (data[0] !== 'success') {
                            alert(data[1]);
                        }
                        else {
                            alert('Thanks for your rating!');
							$.mobile.changePage('#profile-page');
                        }
                       },
                       error: function(data) {
                        alert('Service Error');
                       },
                       complete: function(data) {
                        $.mobile.loading('hide');
                       }
    });
}
